﻿using System.Collections.Generic;
using System.Linq;
using System.Threading;

using DbLayer;
using WordStat.Tasks;

namespace WordStat.Anylize
{
    internal sealed class PageService
    {
        internal static void PerformTasks(IEnumerable<Task> list)
        {
            int index = 0;
            foreach (var task in list)
            {
                if (!task.IsAnalyzed)
                {
                    try
                    {
                        PerformTask(task);
                        task.IsAnalyzed = true;
                    }
                    catch
                    {
                        task.IsAnalyzed = false;
                    }
                }

                index++;

                Thread.Sleep(5000);
            }
        }

        private static void PerformTask(Task task)
        {
            var article = NetService.PageService.GetArticleData(task.Url);

            if (article == null)
                return;

            var keysToDelete = article.Words.Keys.Where(IsToDelete).ToList();

            foreach (var key in keysToDelete)
                article.Words.Remove(key);

            AdoProxy.AddArticleDb(article);
        }

        private static bool IsToDelete(string word)
        {
            if (string.IsNullOrEmpty(word))
                return true;

            if (word.Length == 1)
                return true;

            if (word.Contains("&nbsp"))
                return true;

            if (word.Contains("&quot"))
                return true;

            int res;
            if (int.TryParse(word, out res))
                return true;

            return false;
        }
    }
}
